package com.appkubes.mall.restful.application.pay.strategy.alipay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.appkubes.common.Response;
import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.mall.core.entity.MallPayRecord;
import com.appkubes.mall.core.entity.MallSystem;
import com.appkubes.mall.restful.application.pay.strategy.alipay.service.AliPayService;
import com.appkubes.mall.restful.application.pay.strategy.wxpay.model.AliModel;
import com.appkubes.mall.restful.application.system.basic.service.SystemService;
import com.appkubes.mall.restful.application.system.config.service.impl.ConfigServiceImpl;
import com.appkubes.mall.restful.application.wx.service.impl.PayRecordServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    SystemService systemService;

    @Autowired
    ConfigServiceImpl configServiceImpl;

    @Autowired
    private PayRecordServiceImpl payRecordServiceImpl;

    @Autowired
    AliModel aliModel;

    /**
     * 支付宝支付
     *
     * @param openid
     * @param payAmount
     * @param orderKey
     * @return
     */
    public Object pay(String openid, BigDecimal payAmount, String orderKey, String type, int appType) {

        if (payAmount.compareTo(BigDecimal.ZERO) != 1) {
            return Response.error(1, "金额有误");
        }

        String outTradeNo = DateUtils.parseDateToStr(new Date(), DateUtils.DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS) + "" + (int) ((Math.random() * 9 + 1) * 100000);
        List<MallPayRecord> list = payRecordServiceImpl.queryAll(" source_key=" + orderKey + " and callback_time>0 order by id desc");
        if (list.size() > 0) {
            MallPayRecord record = list.get(0);
            if (!StringUtils.isEmpty(record.getCallbackXml())) {
                JSONObject jsonobj = JSON.parseObject(record.getCallbackXml());
                if (!StringUtils.isEmpty(jsonobj.getString("result_code"))) {
                    if (jsonobj.getString("result_code").equals("SUCCESS")) {
                        return Response.error(1, "该单已支付");
                    }
                }
            }
        }
        MallPayRecord payRecord = new MallPayRecord();
        payRecord.setSourceType(type);
        payRecord.setSourceKey(orderKey);
        payRecord.setPayMoney(payAmount);
        payRecord.setPayTime(DateUtils.DateToTimestamp(new Date()));
        payRecord.setOpenid(openid);
        payRecord.setNo(outTradeNo);
        payRecordServiceImpl.add(payRecord);

        //获得初始化的AlipayClient
        MallSystem aliConfig = systemService.queryAll(" platform='alipay'  order by `sort` desc ").get(0);
        String returnUrl = configServiceImpl.getByKey("credit_return_url", "");
        returnUrl = returnUrl.replace("{orderid}", orderKey + "");
        String gatewayUrl = "https://openapi.alipay.com/gateway.do";
        String chatSet = "UTF-8";
        String signType = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, aliConfig.getAppid(), aliConfig.getAliRsaprivatekey(), "json", chatSet, aliConfig.getAliAlipayrsapublickey(), signType);
        String bizContent = "";
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        switch (appType) {
            case 1:
                alipayRequest.setNotifyUrl(aliModel.getNotifyUrl());
                bizContent = "{\"body\":" + payRecord.getPayrecordKey() + ","
                        + "\"subject\": \"App支付\","
                        + "\"out_trade_no\": " + outTradeNo + ","
                        + "\"timeout_express\": \"30m\","
                        + "\"total_amount\": " + payAmount + ","
                        + "\"product_code\":\"QUICK_MSECURITY_PAY\""
                        + "}";
                alipayRequest.setBizContent(bizContent);
                try {
                    String response = alipayClient.sdkExecute(alipayRequest).getBody();
                    return response;
                } catch (AlipayApiException e) {
                    e.printStackTrace();
                }
                break;
            case 2:
                bizContent = "{\"body\":" + payRecord.getPayrecordKey() + ","
                        + "\"subject\": \"H5支付\","
                        + "\"out_trade_no\": " + outTradeNo + ","
                        + "\"timeout_express\": \"30m\","
                        + "\"total_amount\": " + payAmount + ","
                        + "\"product_code\":\"QUICK_MSECURITY_PAY\""
                        + "}";
                alipayRequest.setBizContent(bizContent);
                alipayRequest.setNotifyUrl(aliModel.getNotifyUrl());
                alipayRequest.setReturnUrl(returnUrl);
                try {
                    String response = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
                    return response;
                } catch (AlipayApiException e) {
                    e.printStackTrace();
                }
                break;
        }
        return "";
        /**
         alipayRequest.setReturnUrl(AlipayConfig.return_url);
         alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

         //商户订单号，商户网站订单系统中唯一订单号，必填
         String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
         //付款金额，必填
         String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
         //订单名称，必填
         String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
         //商品描述，可空
         String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

         alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
         + "\"total_amount\":\""+ total_amount +"\","
         + "\"subject\":\""+ subject +"\","
         + "\"body\":\""+ body +"\","
         + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

         //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
         //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
         //		+ "\"total_amount\":\""+ total_amount +"\","
         //		+ "\"subject\":\""+ subject +"\","
         //		+ "\"body\":\""+ body +"\","
         //		+ "\"timeout_express\":\"10m\","
         //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
         //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

         //请求
         String form="";
         try {
         form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
         } catch (AlipayApiException e) {
         e.printStackTrace();
         }
         return form;
         **/
        //return openid+"----"+payAmount+"---"+orderId+"-----"+appType+"----"+platUuid;
    }

}
